package pl.matt.model;

import java.util.Collection;
import java.util.HashSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Min;

import org.apache.commons.collections.CollectionUtils;

@NamedQueries({
	@NamedQuery(name="Frame.findByVideoName", query="FROM Frame f WHERE f.video.name = ?"),
	@NamedQuery(name="Frame.findByVideoNameOrderByNumber", query="FROM Frame f WHERE f.video.name = ? ORDER BY number")
})
@Entity
@Table(name="frames", uniqueConstraints=@UniqueConstraint(columnNames={"number","video_id"}))
public class Frame extends AbstractEntity {
	
	@Min(0)
	private int width;
	
	@Min(0)
	private int height;	
	
	@Min(0)
	private int number;
	
	@Column(name="file_path")
	private String filePath;

	@ManyToOne(optional=false)
	@JoinColumn(name="video_id")
	private Video video;

	@OneToMany(mappedBy="frame")
	private Collection<FrameRegion> frameRegions = new HashSet<FrameRegion>();
	
	public Frame() {
		
	}
	
	public Frame(int number) {
		this.number = number;
	}
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public Video getVideo() {
		return video;
	}

	public void setVideo(Video video) {
		this.video = video;
	}

	public Collection<FrameRegion> getFrameRegions() {
		return frameRegions;
	}

	public void setFrameRegions(Collection<FrameRegion> frameRegions) {
		this.frameRegions = frameRegions;
	}	
	
	public FrameRegion getVerifiedRegion() {
		if (CollectionUtils.isNotEmpty(frameRegions)) {
			for (FrameRegion fr : frameRegions) {
				if (fr.isVerified()) {
					return fr;
				}
			}
		}
		return null;
	}
	
}
